home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Pascal Super Library
/
Pascal Super Library (CW International)(1997).bin
/
LIBRARY
/
PAS_0693
/
RDASCIIZ.PAS
< prev
next >
Wrap
Pascal/Delphi Source File
|
1993-06-30
|
3KB
|
76 lines
{─ Fido Pascal Conference ────────────────────────────────────────────── PASCAL ─
Msg : 462 of 474
From : Dj Murdoch 1:249/99.5 27 Jun 93 08:12
To : Todd Holmes
Subj : Unit Cstr: Nul term strings for streams
────────────────────────────────────────────────────────────────────────────────
TH> Cstr is a unit to suppliment the writing and reading of Nul terminating
TH> strings to and from Streams. Cstr also offers conversion
TH> from Pascal strings
TH> to Nul term Strings.
TH> Function LoadCStr(Var S:TStream): PChar;
TH> var
TH> Start,Stop: LongInt;
TH> L: Word;
TH> Buf: Char;
TH> CStr: PChar;
TH> begin
TH> Start := S.GetPos;
TH> Repeat {Scan for end of string, (nul term char: #0)
TH> S.Read(Buf,1); no need for a larger buffer, since were using
TH> TBufStream with a 1 k buffer
TH> Until Buf = #0;
TH> Stop := S.GetPos;
TH> if (stop - Start) > MaxLen then LoadCStr := Nil {string is to big!
TH> {Needs additon error checking here
TH> Else
TH> begin
TH> L := Stop - Start; {Get Length of string, include nul terminator
TH> GetMem(CStr,L); {Allocate memory
TH> S.Seek(Start); {repostion
TH> S.Read(CStr^,L); {Read the string
TH> LoadCStr := CStr;
TH> end;
TH> end; {LoadCstr}
{
The trouble with this kind of approach is that it's really slow, and doesn't
work on streams that don't support Seek. Even if you're using something like
TBufStream that does support Seek, it's a very slow operation: every call to
Seek flushes the buffer, and the next read will reload it all from disk. So,
for example, to read a series of 3 character null-terminated strings, you'd do
a 1K read to reload the buffer on *every* call to LoadCStr.
I don't know a good way to read Asciiz strings, but I think it's worth
requiring the caller to supply the buffer: at least then you only have to make
one pass through the file, and if it's a buffered stream, you don't flush the
buffer. You might want to offer that *in addition* to the LoadCStr procedure,
because sometimes the caller knows an adequate buffer size, and sometimes it
doesn't.
Here's the one I use:}
function ReadAsciiz(S : PStream;var Buffer;MaxLen:word):Word;
var
size : word;
streamsize : longint;
c : char;
resultbytes : TByteArray absolute buffer;
begin
size := 0;
c := #1;
while (c <> #0) and (size < Maxlen) and (S^.Status = stOK) do
begin
S^.Read(c,1);
resultbytes[size] := byte(c);
inc(size);
end;
if c <> #0 then
begin
resultbytes[size] := 0;
s^.Reset;
end
else
dec(size);
ReadAsciiz := size;
end;